<template>
  <el-form label-width="100px" ref="formRef" :model="dataForm" :rules="dataRule">
    <el-card class="box-card" shadow="never">
      <div class="text item">
        <el-row>
          <el-col :span="4">
            <el-form-item :label="i18n('product.picture')" prop="picture">
              <el-upload
                class="avatar-uploader"
                :action="$http.adornUrl('/file/picture')"
                :show-file-list="false"
                :headers="upload_headers"
                :on-success="handlePictureSuccess"
                :before-upload="beforePictureUpload">
                <img v-if="dataForm.picture" :src="dataForm.picture" class="avatar-upload"/>
                <el-icon v-else class="avatar-uploader-icon"><Plus/></el-icon>
              </el-upload>
              <el-link @click="handlePictureRemove" type="danger">
                {{ i18n('common.delete') }}
              </el-link>
            </el-form-item>
          </el-col>
          <el-col :span="20">
            <el-row :gutter="20">
              <el-col :span="8">
                <el-form-item :label="i18n('product.title')" prop="title">
                  <el-input
                    v-model="dataForm.title"
                    :placeholder="i18n('common.please_input') + i18n('product.title')" clearable></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item :label="i18n('product.short_title')" prop="short_title">
                  <el-input
                    v-model="dataForm.short_title"
                    :placeholder="i18n('common.please_input') + i18n('product.short_title')" clearable></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="8">
                <el-form-item :label="i18n('product.module_id')" prop="module_id">
                  <el-select
                    v-model="dataForm.module_id"
                    :placeholder="i18n('common.please_select') + i18n('product.module_id')"
                    @change="loadCategoryList"
                    clearable>
                    <el-option v-for="(v, k) in moduleList" :label="v.title" :key="k" :value="v.id"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item :label="i18n('product.category_id')" prop="category_id">
                  <el-select
                    v-model="dataForm.category_id"
                    :placeholder="i18n('common.please_select') + i18n('product.category_id')" clearable>
                    <el-option v-for="(v, k) in categoryList" :label="v.title" :key="k" :value="v.id"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item :label="i18n('product.label_id')" prop="label_id">
                  <el-select
                    v-model="dataForm.label_id"
                    :placeholder="i18n('common.please_select') + i18n('product.label_id')"
                    collapse-tags
                    multiple clearable>
                    <el-option v-for="(v, k) in labelList" :label="v.title" :key="k" :value="v.id"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="24">
                <el-form-item :label="i18n('product.description')" prop="description">
                  <el-input
                    type="textarea"
                    v-model="dataForm.description"
                    :rows="5"
                    show-word-limit
                    maxlength="500"
                    :placeholder="i18n('common.please_input') + i18n('product.description')">
                  </el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="24">
                <el-form-item :label="i18n('product.feature')" prop="feature">
                  <el-input
                    type="textarea"
                    v-model="dataForm.feature"
                    :rows="5"
                    show-word-limit
                    maxlength="500"
                    :placeholder="i18n('common.please_input') + i18n('product.feature')">
                  </el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="8">
                <el-form-item :label="i18n('product.hot')" prop="hot">
                  <el-input-number v-model="dataForm.hot" :min="0.0" :max="5.0" :precision="1" :step="0.1">
                  </el-input-number>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item :label="i18n('product.score')" prop="score">
                  <el-input-number v-model="dataForm.score" :min="0.0" :max="5.0" :precision="1" :step="0.1">
                  </el-input-number>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item :label="i18n('common.sort')" prop="sort">
                  <el-input-number v-model="dataForm.sort" :min="0">
                  </el-input-number>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="8">
                <el-form-item :label="i18n('product.is_recommend')" prop="is_recommend">
                  <el-switch
                    v-model="dataForm.is_recommend"
                    active-value="1"
                    :active-text="i18n('common.yes')"
                    inactive-value="2"
                    :inactive-text="i18n('common.no')">
                  </el-switch>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item :label="i18n('common.is_hidden')" prop="is_hidden">
                  <el-switch
                    v-model="dataForm.is_hidden"
                    active-value="1"
                    :active-text="i18n('common.yes')"
                    inactive-value="2"
                    :inactive-text="i18n('common.no')">
                  </el-switch>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item :label="i18n('common.status')" prop="status">
                  <el-switch
                    v-model="dataForm.status"
                    active-value="1"
                    :active-text="i18n('common.enable')"
                    inactive-value="2"
                    :inactive-text="i18n('common.disable')">
                  </el-switch>
                </el-form-item>
              </el-col>
            </el-row>
          </el-col>
        </el-row>
      </div>
    </el-card>

    <el-card class="box-card mt10" shadow="never">
      <template v-slot:header>
        <div class="clearfix">
          <span>{{ i18n('product.resource_info') }}</span>
        </div>
      </template>
      <div class="text item">
        <el-row>
          <el-col :span="4">
            <el-form-item :label="i18n('product.video')" prop="video">
              <el-upload
                class="avatar-uploader"
                :action="$http.adornUrl('/file/file')"
                :show-file-list="false"
                accept=".mp4"
                :headers="upload_headers"
                :on-success="handleVideoSuccess"
                :on-remove="handleVideoRemove">
                <video class="form-upload-video" :auto-play="false" v-if="dataForm.video" :src="dataForm.video"/>
                <el-icon v-else class="avatar-uploader-icon"><Plus/></el-icon>
              </el-upload>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item :label="i18n('product.scheme')" prop="scheme">
              <el-upload
                class="avatar-uploader"
                :action="$http.adornUrl('/file/file')"
                :show-file-list="false"
                 accept=".pdf,.docx,.doc,.ppt,.pptx"
                :headers="upload_headers"
                :on-success="handleSchemeSuccess"
                :on-remove="handleSchemeRemove">
                <img v-if="dataForm.scheme" src="@/assets/images/default/file.png" class="avatar-upload"/>
                <el-icon v-else class="avatar-uploader-icon"><Plus/></el-icon>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
      </div>
    </el-card>

    <el-card class="box-card mt10" shadow="never">
      <div class="text item">
        <el-form-item>
          <el-button
            type="primary"
            @click="dataFormSubmit(formRef)">
            {{ i18n('common.confirm') }}
          </el-button>
          <el-button @click="resetForm(formRef)">
            {{ i18n('common.reset') }}
          </el-button>
        </el-form-item>
      </div>
    </el-card>
  </el-form>
</template>

<script setup name="product-basic-form">
  import { useBase } from "@/hooks/base/useBase"
  import { useForm } from "@/hooks/form/useForm"
  import { useUpload } from "@/hooks/upload/useUpload"

  const { router, query, i18n, isAuth } = useBase()

  const props = defineProps({
    model: {
      type: [String, Object],
      default: null,
    }
  });

  const id = ref(0)
  const moduleList = ref([])
  const categoryList = ref([])
  const labelList = ref([])
  const attachmentList = ref([])

  const dataForm = reactive({
    id: 0,
    category_id: '',
    label_id: [],
    picture: '',
    video: '',
    scheme: '',
    title: '',
    short_title: '',
    description: '',
    feature: '',
    hot: 0.0,
    score: 0.0,
    sort: 0,
    is_recommend: '2',
    is_hidden: '2',
    status: '1',
  })

  const dataRule = reactive({
    picture: [{
      required: true,
      message: i18n('product.rules.picture.require'),
      trigger: 'blur',
    }],
    title: [{
      required: true,
      message: i18n('product.rules.title.require'),
      trigger: 'blur',
    }],
    module_id: [{
      required: true,
      message: i18n('product.rules.module_id.require'),
      trigger: 'blur',
    }],
    category_id: [{
      required: true,
      message: i18n('product.rules.category_id.require'),
      trigger: 'blur',
    }],
    description: [{
      required: true,
      message: i18n('product.rules.description.require'),
      trigger: 'blur',
    }],
  })

  const dataPreview = reactive({
    status: false,
    url: '',
  })

  // 使用defineExpose暴露content
  defineExpose({
    id
  });

  const emits = defineEmits(['changeStatus'])

  const {
    formRef,
    resetForm
  } = useForm(props.model, dataForm)

  const {
    upload_headers,
    handlePictureSuccess,
    beforePictureUpload,
  } = useUpload(dataForm, dataPreview)

  const init = (form) => {
    dataForm.id = query.id || 0

    nextTick(() => {
      form.value.resetFields()
      if (dataForm.id) {
        $http({
          url: $http.adornUrl(`/${props.model}/view/${dataForm.id}`),
          method: 'get',
          params: $http.adornParams({}),
        }).then(({ data }) => {
          if (data && data.status === 200) {
            dataForm.id = data.data.id
            dataForm.module_id = data.data.module_id
            dataForm.category_id = data.data.category_id
            dataForm.picture = data.data.picture
            dataForm.video = data.data.video
            dataForm.scheme = data.data.scheme
            dataForm.title = data.data.title
            dataForm.short_title = data.data.short_title
            dataForm.description = data.data.description
            dataForm.feature = data.data.feature
            dataForm.hot = data.data.hot
            dataForm.score = data.data.score
            dataForm.sort = data.data.sort
            dataForm.is_recommend = data.data.is_recommend.value + ''
            dataForm.is_hidden = data.data.is_hidden.value + ''
            dataForm.status = data.data.status.value + ''
          }
        }).then(() => {
          if (dataForm.id) {
            $http({
              url: $http.adornUrl(`/${props.model}/label/select`),
              method: 'get',
              params: $http.adornParams({
                product_id: dataForm.id,
              }),
            }).then(({ data }) => {
              if (data && data.status === 200) {
                data.data.forEach((res) => {
                  dataForm.label_id.push(res.label_id)
                })
              }
            })
          }
        }).then(() => {
          if (dataForm.module_id) {
            $http({
              url: $http.adornUrl(`/${props.model}/category/select`),
              method: 'get',
              params: $http.adornParams({
                module_id: dataForm.module_id,
              }),
            }).then(({ data }) => {
              if (data && data.status === 200) {
                categoryList.value = data.data
              }
            })
          }
        })
      }
    })
  }

  // 表单提交
  const dataFormSubmit = (form) => {
    form.validate(async (valid, fields) => {
      if (valid) {
        $http({
          url: $http.adornUrl(`/${props.model}/frist_submit`),
          method: 'post',
          data: $http.adornData({
            id: dataForm.id || undefined,
            module_id: dataForm.module_id,
            category_id: dataForm.category_id,
            label_id: dataForm.label_id,
            title: dataForm.title,
            short_title: dataForm.short_title,
            description: dataForm.description,
            feature: dataForm.feature,
            picture: dataForm.picture,
            video: dataForm.video,
            scheme: dataForm.scheme,
            hot: dataForm.hot,
            score: dataForm.score,
            sort: dataForm.sort,
            is_recommend: dataForm.is_recommend,
            is_hidden: dataForm.is_hidden,
            status: dataForm.status,
          }),
        }).then(({ data }) => {
          if (data && data.status === 200) {
            $message.success(i18n('common.handle_success'))
            id.value = data.data.id
            emits('changeStatus', false)
          } else {
            $message.error(data.message)
          }
        })
      }
    })
  }

  const loadModuleList = () => {
    $http({
      url: $http.adornUrl('/business/product/module/select'),
      method: 'get',
    }).then(({ data }) => {
      if (data && data.status === 200) {
        moduleList.value = data.data
      } else {
        $message.error(data.message)
      }
    })
  }

  const loadCategoryList = (module_id) => {
    $http({
      url: $http.adornUrl('/business/product/category/select'),
      method: 'get',
      params: $http.adornParams({
        module_id: module_id
      }),
    }).then(({ data }) => {
      if (data && data.status === 200) {
        categoryList.value = data.data
        dataForm.category_id = ''
      } else {
        $message.error(data.message)
      }
    })
  }

  const loadLabelList = () => {
    $http({
      url: $http.adornUrl('/business/label/select'),
      method: 'get',
      params: $http.adornParams({
        'type': 1
      }),
    }).then(({ data }) => {
      if (data && data.status === 200) {
        labelList.value = data.data
      } else {
        $message.error(data.message)
      }
    })
  }

  const handlePictureRemove = () => {
    dataForm.picture = ''
  }

  const handleVideoSuccess = (res, file) => {
    dataForm.video = res.data
  }

  const handleSchemeSuccess = (res, file) => {
    dataForm.scheme = res.data
  }

  const handleVideoRemove = (res, file) => {
    dataForm.video = ''
  }

  const handleSchemeRemove = (res, file) => {
    dataForm.scheme = ''
  }

  onMounted(() => {
    init(formRef)

    loadModuleList()
    loadLabelList()
  })
</script>
